package cn.lh.user.controller;

import cn.lh.basic.util.JsonResult;
import cn.lh.basic.util.Page;
import cn.lh.org.exception.BusinessException;
import cn.lh.user.domain.User;
import cn.lh.user.dto.UserDto;
import cn.lh.user.query.UserQuery;
import cn.lh.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") long id) {
        return userService.findById(id);
    }

    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") long id) {
        try {
            userService.del(id);
            return JsonResult.set(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "删除失败");
        }

    }

    @PutMapping
    public JsonResult addOrUpdate(@RequestBody User user) {
        try {
            if (user.getId() == null) {
                userService.add(user);
            } else {
                userService.update(user);
            }
            return JsonResult.set(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "操作失败");
        }

    }

    @PostMapping
    public Page<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryPage(query);
    }

    @PatchMapping
    public JsonResult batchDelete(@RequestBody Long[] ids){
        try {
            userService.batchDelete(ids);
            return JsonResult.set(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "删除失败");
        }
    }

    @PostMapping("/phone/register")
    public JsonResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return JsonResult.set(true, "注册成功");
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.set(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "系统错误稍后重试");
        }
    }

}
